import { fetchVbidInfo } from ".";
import { encWbi, getWbiKeys } from "./wbi";
import _ from 'lodash'

export const BVID_MAP_COMMENTS = 'bvid_map_comments'

/**
 * 获取投稿视频的评论
 * @param bvid
 * @returns
 */
export const getBvidComments = async (bvid: string) => {
    const result = await chrome.storage.local.get([BVID_MAP_COMMENTS])
    const web_keys = await getWbiKeys()
    const
        img_key = web_keys.img_key,
        sub_key = web_keys.sub_key

    const map = result[BVID_MAP_COMMENTS] ?? {}
    if (map[bvid]) {
        return map[bvid]
    } else {
        const { aid: oid } = await fetchVbidInfo(bvid)
        let replies = [] as any[]
        let list = replies
        let pn = 1
        try {
            do {
                const params = { oid, type: 1, ps: 20, pn, sort: 1 }
                const query = encWbi(params, img_key, sub_key)
                replies = await fetchComments(query)
                list = list.concat(replies)
                pn++
            } while (replies.length != 0 && pn < 30)
        } catch (error) {
            console.log(error);

        }
        map[bvid] = processComments(list);
        chrome.storage.local.set({ [BVID_MAP_COMMENTS]: map })
        return map[bvid]
    }
}

/**
 * 请求投稿视频的评论
 */
export const fetchComments = async (query: string) => {
    const res = await fetch(`https://api.bilibili.com/x/v2/reply?${query}`).then((res) => res.json());
    return res?.data?.replies || []

}

/**
 * 处理字幕
 */
export const processComments = (comments: any[]) => {
    return comments.map(comment => {
        const { reply_control, member, content, replies } = comment;
        const { time_desc, location } = reply_control
        return {
            commenter: member.uname,
            commentContent: content.message,
            time_desc,
            location,
            replies: _.map(replies, reply => {
                const { reply_control, member, content } = reply;
                const { time_desc, location } = reply_control
                return {
                    commenter: member.uname,
                    commentContent: content.message,
                    time_desc,
                    location,
                };
            })
        };
    });
}




